package cn.okcode.api.framework;

import org.apache.logging.log4j.Logger;

/**
 * 包装的日志类
 * 增加了收集日志功能
 */
public class TraceLogger {
    //记录错误信息
    private static final ThreadLocal<StringBuilder> MESSAGE_LOCAL = new ThreadLocal<>();

    private final Logger logger;

    public static String getMessage() {
        StringBuilder stringBuilder = MESSAGE_LOCAL.get();
        if (stringBuilder == null) {
            return "";
        }
        return stringBuilder.toString();
    }

    public static void removeMessage() {
        MESSAGE_LOCAL.remove();
    }

    public TraceLogger(Logger logger) {
        this.logger = logger;
    }

    public void raiseException(String message) {
        appendError(message);
        throw new Jsp2ApiException(message);
    }

    public boolean isDebugEnabled() {
        return logger.isDebugEnabled();
    }

    public void debug(Object message) {
        logger.debug(message);
        appendDebug(message.toString());
    }

    public void debug(String message) {
        logger.debug(message);
        appendDebug(message);
    }

    public void error(String message) {
        logger.error(message);
        appendError(message);
    }

    public void error(Throwable throwable, String message) {
        logger.error(message, throwable);
        appendError(message);
    }

    private void appendError(String message) {
        StringBuilder messageBuilder = getMessageBuilder();
        messageBuilder.append(System.lineSeparator());
        messageBuilder.append("[ERROR]:");
        messageBuilder.append(message);
    }

    private void appendDebug(String message) {
        StringBuilder messageBuilder = getMessageBuilder();
        messageBuilder.append(System.lineSeparator());
        messageBuilder.append("[DEBUG]:");
        messageBuilder.append(message);
    }

    private StringBuilder getMessageBuilder() {
        StringBuilder messageBuilder = MESSAGE_LOCAL.get();
        if (messageBuilder == null) {
            messageBuilder = new StringBuilder();
            MESSAGE_LOCAL.set(messageBuilder);
        }
        return messageBuilder;
    }
}
